package rrrmai.activity;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Menu;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;
import com.jakewharton.rxbinding2.support.v7.widget.RxToolbar;
import com.jakewharton.rxbinding2.view.RxView;
import com.xgggh.rrrmai.BR;
import com.xgggh.rrrmai.R;
import com.xgggh.rrrmai.databinding.ActivityPostBinding;
import java.util.UUID;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import rrrmai.model.User;
import rrrmai.viewbinder.Comment;
import rrrmai.viewbinder.Post;
import rrrmai.viewmodel.PostsViewModel;
import xgggh.activity.BaseActivity;

/**
 * @title  添加评价
 */
public class PostActivity extends BaseActivity {
    private static final int ContactRequest=0;
    private static final int PostRequest=1;

    ActivityPostBinding mBinding;
    Comment mComment  = new Comment();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding=DataBindingUtil.setContentView(this,R.layout.activity_post);
        setSupportActionBar(mBinding.toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mBinding.setVariable(BR.comment,mComment);
        onClick();
        onListener();
    }

    private  void onListener(){
        RxToolbar.itemClicks(mBinding.toolbar)
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindToLifecycle())
                .subscribe(menuItem -> {
                    int itemId=menuItem.getItemId();
                    switch (itemId){
                        case R.id.action_send:
                            actionSend();
                            break;
                    }
                });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_send,menu);
        return true;
    }

    private void actionSend(){
        //checklist
        boolean pass=checkList();
        if (!pass){
            return;
        }
        //close input method
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mBinding.getRoot().getWindowToken(), 0);
        //dialog
        Intent intent = new Intent(this,WorthActivity.class);
        intent.putExtra("data",mComment);
        startActivityForResult(intent,PostRequest);
    }


    private boolean checkList(){
        boolean checked=true;
        if (TextUtils.isEmpty(mComment.getContent())){
            Toast.makeText(this, "内容不能为空", Toast.LENGTH_SHORT).show();
            checked=false;
        }else if (TextUtils.isEmpty(mComment.getUserMobile())){
            Toast.makeText(this, "评价对象不能为空", Toast.LENGTH_SHORT).show();
            checked=false;
        }
        return checked;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode==ContactRequest) {
            ContentResolver reContentResolverol = getContentResolver();
            Uri contactData = data.getData();

            Cursor cursor = managedQuery(contactData, null, null, null, null);
            cursor.moveToFirst();
            String username = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = reContentResolverol.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId,
                    null,
                    null);
            while (phone.moveToNext()) {
                String usernumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                mComment.setUserMobile(usernumber);
                mComment.setUserName(username);
            }

        }else  if (resultCode == Activity.RESULT_OK && requestCode==PostRequest) {
            finish();
        }
    }

    private void onClick(){
        io.reactivex.Observable.merge(RxView.clicks( mBinding.contentPost.name)
                ,RxView.clicks( mBinding.contentPost.mobile))
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        Intent intent = new Intent( PostActivity.this, FollowActivity.class);
                        startActivity(intent);
                    }
                });

        RxView.clicks( mBinding.contentPost.contact)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        boolean pass= permisson(PostActivity.this, Manifest.permission.READ_CONTACTS);
                        if (pass){
                            choiceContact();
                        }
                    }
                });
    }


    private void choiceContact(){
        startActivityForResult(new Intent(
                Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), ContactRequest);
    }

    private boolean permisson(Activity context, String permission){
        String[] permissons= new String[]{permission};
        int granted=  ActivityCompat.checkSelfPermission(context,permission);
        if (granted== PackageManager.PERMISSION_GRANTED){//授权成功
            return true;
        }else{//授权拒绝-并且不再弹出对话框
            if (ActivityCompat.shouldShowRequestPermissionRationale(context, permission)) {
                shouldShowRationale(context,110, permission);
            } else {//授权选择了
                ActivityCompat.requestPermissions(context, permissons, 110);
            }
        }
        return false;
    }


    private void shouldShowRationale(Activity context, int requestCode , String requestPermission){
        new AlertDialog.Builder(context)
                .setTitle("权限选择")
                .setMessage("读取通讯录权限!")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        ActivityCompat.requestPermissions(context,
                                new String[]{requestPermission},
                                requestCode);
                    }
                }).setNegativeButton("取消", (dialog, which) -> {
            Toast.makeText(context, "应用无法使用", Toast.LENGTH_SHORT).show();
            dialog.dismiss();
        }).show();
    }

}
